<template>
  <div class="page-container">
    <!-- 头部导航 -->
    <header class="header">
      <BackBtn />
      <h1>提案分流管理</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-input 
          v-model="searchText" 
          placeholder="支持搜索案由、提案人、提案号" 
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button 
              type="button" 
              class="search-btn"
              @click="handleSearch"
            >
              <el-icon class="search-icon">
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>

        <div class="filter-section">
          <!-- 日期范围选择 -->
          <div class="date-range-picker">
            <el-date-picker 
              v-model="dateRange[0]" 
              type="date" 
              placeholder="开始日期" 
              class="date-picker"
              @change="handleFilterChange" 
            />
            <span class="separator">—</span>
            <el-date-picker 
              v-model="dateRange[1]" 
              type="date" 
              placeholder="结束日期" 
              class="date-picker"
              @change="handleFilterChange" 
            />
          </div>

          <!-- 时间选择 -->
          <el-select v-model="sortBy" placeholder="排序：提案时间(倒序)" @change="handleFilterChange">
            <el-option label="提案时间(倒序)" value="desc" />
            <el-option label="提案时间(正序)" value="asc" />
          </el-select>

          <!-- 类型筛选 -->
          <div class="advanced-filters">
            <el-select v-model="proposalType" @change="handleFilterChange" placeholder="提案类型：全部">
              <el-option label="类型筛选：全部" value="all" />
              <el-option label="医疗健康类" value="医疗健康类" />
              <el-option label="教育科技类" value="教育科技类" />
              <el-option label="文化体育类" value="文化体育类" />
              <el-option label="城市建设类" value="城市建设类" />
              <el-option label="环境保护类" value="环境保护类" />
              <el-option label="社会治理类" value="社会治理类" />
              <el-option label="经济发展类" value="经济发展类" />
              <el-option label="其他类" value="其他类" />
            </el-select>
          </div>

          <!-- 状态筛选 -->
          <el-select v-model="status" @change="handleFilterChange" placeholder="状态筛选：全部">
            <el-option label="状态筛选：全部" value="all" />
            <el-option label="已通过" value="分流" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>

          <!-- 导出按钮 -->
          <el-button type="danger" style="margin-left: auto" @click="handleExport">导 出</el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(0,0,0,0)">
        <div class="news-list">
          <!-- 添加表头 -->
          <div class="news-header">
            <div class="header-item">案由</div>
            <div class="header-item">提案类型</div>
            <div class="header-item">提案人</div>
            <div class="header-item">提案时间</div>
            <div class="header-item">操作</div>
          </div>
          <!-- 无数据显示 -->
          <div v-if="!tableData || tableData.length === 0" class="no-data">
            <el-empty description="暂无数据" />
          </div>
          <!-- 数据列表 -->
          <div v-else v-for="(item, index) in tableData" :key="index" class="news-item">
            <div class="line"></div>
            <div class="news-info" @click="handleRowClick(item)">
              <div class="info-value" style="flex: 2">
                {{ item.caseReason }}
                <span v-if="item.isCancel" class="cancel-tag">申请取消</span>
              </div>
              <div class="info-value">{{ item.proposalType }}</div>
              <div class="info-value">{{ item.proposer }}</div>
              <div class="info-value">{{ formatDate(item.recheckTime) }}</div>
            </div>
            <div class="news-actions">
              <!-- 驳回按钮 -->
              <el-button
                v-if="['复审'].includes(item.status)"
                type="danger"
                @click="handleReject(item)"
              >
                驳回
              </el-button>
              <el-button
                v-if="item.status === '已驳回'"
                type="danger"
                disabled
              >
                已驳回
              </el-button>
              
              <!-- 通过按钮 -->
              <el-button
                v-if="['复审'].includes(item.status)"
                type="success"
                @click="handleApprove(item)"
              >
                分流
              </el-button>
              <el-button
                v-if="['分流','专项处理', '最终批复','处理完结'].includes(item.status)"
                type="success"
                disabled
              >
                已分流
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 10, 15]"
            :background="false"
            layout="prev, pager, next, jumper"
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, h } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage, ElSelect, ElOption } from 'element-plus'
import { updateProposalStatus, getProList, exportProposals } from '@/api/proposal.js'
import { useProposalStore } from '@/stores/proposal.js'
import { storeToRefs } from 'pinia'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'

// 使用 proposal store
const proposalStore = useProposalStore()

// 使用 store 中的状态
const { 
  tableData,
  total,
  pageNum,
  pageSize,
  dateRange,
  sortBy,
  status,
  proposalType,
  searchText
} = storeToRefs(proposalStore)

// 筛选
const router = useRouter()
const loading = ref(false)

// 重置所有筛选条件的函数
const resetFilters = () => {
  searchText.value = ''  // 重置搜索文本
  dateRange.value = [null, null]  // 重置日期范围
  sortBy.value = 'desc'  // 重置时间排序为默认的倒序
  proposalType.value = 'all'  // 重置提案类型为全部
  status.value = 'all'  // 重置状态筛选为全部
  pageNum.value = 1
}

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}/${month}/${day} ${hours}:${minutes}`;
}

// 在组件挂载时获取提案数据
onMounted(() => {
  resetFilters()  // 初始化重置
  loading.value = true
  proposalStore.fetchProposalData()
  loading.value = false
})

// 分页处理
const onSizeChange = (size) => {
  pageSize.value = size
  proposalStore.fetchProposalData()
}

const onCurrentChange = (num) => {
  pageNum.value = num
  proposalStore.fetchProposalData()
}

// 筛选条件变化时的处理
const handleFilterChange = () => {
  proposalStore.fetchProposalData()
}


// 处理驳回
const handleReject = async (row) => {
  // 弹出确认窗口
  const confirmResult = await ElMessageBox.confirm(
    `确定要驳回 ${row.proposer} 的提案吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).catch(() => {
    // 用户点击取消时，直接返回
    return false;
  });

  if (confirmResult) {
    try {
      // 更新状态时同时设置 isOr 为 false，pageStatus为3（分流页面）
      await updateProposalStatus({
        pid: row.pid,
        status: '已驳回',
        isOr: false,
        pageStatus: 3
      });
      ElMessage.success(`已驳回 ${row.proposer} 的提案`);
      row.status = '已驳回';
      row.isShunt = false; // 更新本地状态
      // 刷新数据
      proposalStore.fetchProposalData();
    } catch (error) {
      ElMessage.error('驳回提案失败');
    }
  }
};

// 处理分流
const handleApprove = async (row) => {
  try {
    // 获取部门列表
    const response = await getProList();
    const departments = response.data;
    
    // 创建响应式的选择值，如果行项目已有部门则预先选中
    const state = ref({
      selectedDepartment: row.department || ''
    });
    
    ElMessageBox({
      title: state.value.selectedDepartment ? `分流至：${state.value.selectedDepartment}` : '分流至',
      message: h('div', { class: 'shunt-dialog-content' }, [
        h(ElSelect, {
          modelValue: state.value.selectedDepartment,
          'onUpdate:modelValue': value => {
            state.value.selectedDepartment = value;
            // 当部门选择变化时，更新弹窗标题
            document.querySelector('.el-message-box__title').textContent = 
              value ? `分流至：${value}` : '分流至';
          },
          class: 'shunt-select',
          placeholder: '请选择分流部门',
          clearable: false,  // 禁用清除按钮
          filterable: false  // 不需要筛选功能
        }, () => departments.map(dept => 
          h(ElOption, {
            key: dept.id,
            label: dept.name,
            value: dept.name
          })
        ))
      ]),
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '返回',
      customClass: 'shunt-dialog',
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          if (!state.value.selectedDepartment) {
            ElMessage.warning('请选择分流部门');
            return;
          }
          instance.confirmButtonLoading = true;
          try {
            await updateProposalStatus({
              pid: row.pid,
              status: '分流',
              isOr: true,
              pageStatus: 3,
              department: state.value.selectedDepartment
            });
            ElMessage.success(`已将 ${row.proposer} 的提案分流至 ${state.value.selectedDepartment}`);
            row.status = '分流';
            row.isShunt = true;
            row.department = state.value.selectedDepartment;
            proposalStore.fetchProposalData();
            done();
          } catch (error) {
            ElMessage.error('分流失败');
            instance.confirmButtonLoading = false;
          }
        } else {
          // 用户点击返回按钮，直接关闭弹窗，不显示任何错误
          done();
        }
      }
    }).catch(() => {
      // 忽略取消操作的错误，不显示任何提示
    });
  } catch (error) {
    console.error('获取部门列表失败:', error);
    ElMessage.error('获取部门列表失败');
  }
};

// 处理搜索
const handleSearch = () => {
  proposalStore.fetchProposalData()
}

// 处理行点击
const handleRowClick = (row) => {
  router.push(`/proposal/detail/${row.pid}`)
}

// 导出提案数据
const handleExport = async () => {
  try {
    loading.value = true
    
    // 格式化日期参数
    let startDate = null
    let endDate = null
    
    if (dateRange.value[0]) {
      const date = new Date(dateRange.value[0])
      startDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    if (dateRange.value[1]) {
      const date = new Date(dateRange.value[1])
      endDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 准备请求参数，与当前筛选条件保持一致
    const params = {
      pageStatus: 3, // 分流页面
      status: status.value !== 'all' ? status.value : null,
      proposalType: proposalType.value !== 'all' ? proposalType.value : null,
      startDate,
      endDate,
      searchText: searchText.value,
      sort: sortBy.value
    }
    
    // 调用导出API
    const response = await exportProposals(params)
    
    // 创建Blob对象
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 创建临时下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    
    // 设置文件名
    const now = new Date()
    const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`
    link.download = `提案分流数据_${timestamp}.xlsx`
    
    // 模拟点击下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出提案数据成功')
  } catch (error) {
    console.error('导出提案数据失败:', error)
    ElMessage.error('导出提案数据失败')
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
@import '@/assets/css/proposal/list.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/search.css';
@import '@/assets/css/others/select.css';

.cancel-tag {
  display: inline-block;
  background-color: #f56c6c;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
  vertical-align: middle;
}
</style>

<style>
/* 分流弹窗样式 */
.shunt-dialog {
  border-radius: 8px;
  padding: 20px;
}

.shunt-dialog .el-message-box__header {
  padding: 0;
  margin-bottom: 20px;
}

.shunt-dialog .el-message-box__title {
  font-size: 18px;
  font-weight: normal;
  color: #333;
}

.shunt-dialog .el-message-box__headerbtn {
  display: none;
}

.shunt-dialog .el-message-box__content {
  padding: 0;
  margin: 20px 0;
}

.shunt-dialog .el-message-box__message p {
  margin: 0;
}

.shunt-dialog-content {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.shunt-select {
  width: 230px;

}

.shunt-dialog .el-message-box__btns {
  padding: 0;
  margin-top: 20px;
}

.shunt-dialog .el-button {
  padding: 8px 20px;
  min-height: 32px;
  border-radius: 4px;
}

.shunt-dialog .el-button--primary {
  background-color: #c8161d;
  border-color: #c8161d;
}

.shunt-dialog .el-button--primary:hover {
  background-color: #d4383e;
  border-color: #d4383e;
}

.shunt-dialog .el-button--default {
  border-color: #dcdfe6;
}

.shunt-dialog .el-select .el-input__wrapper {
  border-radius: 4px;
}

.shunt-dialog .el-select .el-input__inner {
  height: 40px;
}

.no-data {
  padding: 40px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 4px;
  margin-top: 10px;
}

:deep(.el-empty__description) {
  margin-top: 10px;
  color: #909399;
}
</style>